﻿using Autofac.Core;
using SqlSugar;
using WareHouse.Domain;

namespace WareHose.WebApi.Extensions
{
    /// <summary>
    /// SqlClient
    /// </summary>
    public static class SqlSugarClientExt
    {
        /// <summary>
        /// 注释
        /// </summary>
        /// <param name="services"></param>
        /// <param name="ConnectionString"></param>
        public static void AddSqlSugarClient(this IServiceCollection services,string ConnectionString)
        {
            services.AddScoped<ISqlSugarClient>(s =>
             {
                 //Scoped用SqlSugarClient 
                 SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
                 {
                     DbType = DbType.MySql,
                     ConnectionString = ConnectionString,
                     IsAutoCloseConnection = true,
                 },
                db =>
                {
                    db.QueryFilter.AddTableFilter<ISoftDelete>(it => it.IsDel == false);
                    //每次上下文都会执行

                    //获取IOC对象不要求在一个上下文
                    //var log=s.GetService<Log>()  

                    //获取IOC对象要求在一个上下文
                    var appServive = s.GetService<IHttpContextAccessor>();
                    var log = appServive?.HttpContext?.RequestServices.GetService<ILogger<Program>>();

                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        log?.LogInformation(sql, pars);
                    };
                });
                 return sqlSugar;
             });
        }
    }
}
